var util = require('../../../utils/util.js')
String.prototype.endWith = function (s) {
  if (s == null || s == "" || this.length == 0 || s.length > this.length)
    return false;
  if (this.substring(this.length - s.length) == s)
    return true;
  else
    return false;
  return true;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageHeight: wx.getSystemInfoSync().windowHeight + 50,
    windowHeight: wx.getSystemInfoSync().windowHeight,
    id: '',
    serviceInfo: null,
    serviceInfor: null,
    x: 375,
    y: 480,
    needHelp: false,
    modelPop: true,
    cancelPop: true,
    sharePopup: true, //分享弹窗
    cancelReason: '',
    remarks: '',
    cancelIndex: null,
    popupConfig: {
      title: '提示'
    },
    contentConfig: {
      scoreArray: [
        {
          code: 'product',
          allstars: 5,
          selected: 0,
          index: 0
        },
      ],
      starsize: '77rpx',
      center: true
    },
    modalHidden: true,
    exmeData: {
      "scheme_status": 1,
      "scheme_id": '',
      "order_id": '',
      "order_status": ''
    },
    shareConfig: {
      orderId: 256478,
      type: 1,          //方案类型  1:手术方案  2:产品方案  3:分割方案
      schemeId: 124,     //方案ID
      shareUrl: 'https://www.baidu.com'
    },
    supDescribe: '',
    cancelBtn: [{ title: '我不需要了', check: false }, { title: '计划有变，时间来不及', check: false }, { title: '产品选错了', check: false }, { title: '订单信息填写有误', check: false }, { title: '服务态度不好', check: false }, { title: '其他原因', check: false }],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.globalReview = this.selectComponent('#globalReview')
    this.setData({
      id: options.id
    })
    this.getOrderDetail(this.data.id)
    wx.eventBus.on('getSchemeInfo', (re) => {
      // this.getOrderDetail(this.data.id)
      this.data.serviceInfo.schemeInfo[re].scheme_status = 1
      this.setData({
        serviceInfo: this.data.serviceInfo
      })
      console.log('方案评价', this.data)
    })
    wx.eventBus.on('getOrderEvaluate', (re) => {
      this.setData({
        contentConfig: re.contentConfig,
        supDescribe: re.supDescribe
      })
      console.log('评论新数据', this.data)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.getOrderDetail(this.data.id)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getOrderDetail(this.data.id)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  created: function () {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getOrderDetail(this.data.id)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let url = '/orderDetail?id=' + this.data.id
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
      url = res.target.dataset.url
    }
    return {
      title: '医数聚方案预览',
      path: url,
      success: function (res) {
        console.log(res)
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  caculateScrollPageHeight() { // 计算动态高度
    var me = this
    console.log('可用高度', wx.getSystemInfoSync().windowHeight)
    wx.createSelectorQuery().selectAll('.orderDetail').boundingClientRect(function (rects) {
      rects.forEach(function (rect) {
        console.log('rect', rect.bottom)
        me.setData({
          pageHeight: rect.bottom,
          windowHeight: wx.getSystemInfoSync().windowHeight
        })
        me.caculated = true
        rect.id      // 节点的ID
        rect.dataset // 节点的dataset
        rect.left    // 节点的左边界坐标
        rect.right   // 节点的右边界坐标
        rect.top     // 节点的上边界坐标
        rect.bottom  // 节点的下边界坐标
        rect.width   // 节点的宽度
        rect.height  // 节点的高度
      })
    }).exec()
  },
  // 订单详情
  getOrderDetail: function (id) {
    var self = this
    wx.showLoading({
      title: '正在加载...',
    })
    wx.request({
      url: wx.envConfig.host + '/order/findByOrder?params=' + JSON.stringify({ "order_id": id }) + '&cookiez=' + wx.getStorageSync('cookiez'),
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.error_code === "Y10000") {
          var serviceInfo = res.data.datas.serviceInfo
          serviceInfo.num_pay_money = +res.data.datas.serviceInfo.pay_money
          serviceInfo.pay_money = util.formatMoney(serviceInfo.pay_money) //金额加逗号
          var PayInfo = res.data.datas.serviceInfo.payRecord.find(it => it.type == 2)
          PayInfo ? (serviceInfo.pay_time = util.parseTime(PayInfo.insert_time)) : serviceInfo.pay_time = false;
          serviceInfo.insert_time = util.parseTime(serviceInfo.insert_time) //时间转换
          res.data.datas.serviceInfo.orderStatus = wx.filter.status(res.data.datas.serviceInfo.status) //状态显示
          if (res.data.datas.serviceInfo.type == 5) {
            if (res.data.datas.serviceInfo.status == 2) {
              res.data.datas.serviceInfo.orderStatus = '3D打印中';
            }
          }
          if (res.data.datas.serviceInfo.type == 6 || res.data.datas.serviceInfo.type == 2) {
            if (res.data.datas.serviceInfo.status == 43) {
              res.data.datas.serviceInfo.orderStatus = '待审核分割报告';
            }
          }
          if (res.data.datas.serviceInfo.status == '2' && res.data.datas.serviceInfo.is_urgent_order == '1') {
            res.data.datas.serviceInfo.orderStatus = '等待设计师确认';
          }
          res.data.datas.serviceInfo.schemeInfo = self.handlerSchemes(res.data.datas.schemeInfo) //设计方案
          if (res.data.datas.serviceInfo.schemeInfo && res.data.datas.serviceInfo.status == 6) {
            for (var i = 0; i < res.data.datas.serviceInfo.schemeInfo.length; i++) {
              res.data.datas.serviceInfo.schemeInfo[i].seeScheme = false
              if (res.data.datas.serviceInfo.schemeInfo[i].scheme_status == 0) {
                res.data.datas.serviceInfo.orderStatus = '待审核方案';
              }
            }
          }
          res.data.datas.serviceInfo.schemeUpload = self.schemeInfoFn(res.data.datas.serviceInfo.schemeInfo) //判断是否有文件上传
          res.data.datas.serviceInfo.schemeStatus = self.schemeInfoStatus(res.data.datas.serviceInfo.schemeInfo) //判断文件是否被审核了
          self.setData({
            serviceInfo: serviceInfo,
          })
          if (res.data.datas.serviceInfo.status >= 14 && res.data.datas.serviceInfo.status <= 16) {
            self.getExpress(self.data.id)
          }
          self.findByService(res.data.datas.serviceInfo.service_id)
        }
        self.caculateScrollPageHeight();
        wx.stopPullDownRefresh();
      },
      fail: function ({ errMsg }) {
        console.log('request fail', errMsg);
        wx.stopPullDownRefresh();
      }
    })
  },
  // 物流信息
  getExpress: function (id) {
    var self = this
    wx.request({
      url: wx.envConfig.host + '/order/getTracesInfoImgAndExpressInfo?params=' + JSON.stringify({ "order_Id": id }) + '&cookiez=' + wx.getStorageSync('cookiez'),
      method: 'POST',
      success: function (res) {
        if (res.data.error_code === "Y10000") {
          if (res.data.datas.expressInfoList) {
            res.data.datas.expressInfoList.Traces = res.data.datas.expressInfoList.Traces.reverse()
            self.setData({
              expressInfo: res.data.datas
            })
          }
        }
      },
      fail: function ({ errMsg }) {
        console.log('request fail', errMsg)
      }
    })
  },
  //查看物流图片
  lookExpressImg: function () {
    var url = 'expressImg?id=' + this.data.id;
    wx.navigateTo({
      url: url
    })
  },
  //查看物流信息
  lookExpressList: function () {
    var url = 'expressInfo?id=' + this.data.id;
    wx.navigateTo({
      url: url
    })
  },
  //订单查看服务
  findByService: function (id) {
    var self = this
    wx.request({
      url: wx.envConfig.host + '/service/findByService?params=' + JSON.stringify({ "service_id": id }) + '&cookiez=' + wx.getStorageSync('cookiez'),
      method: 'POST',
      success: function (res) {
        if (res.data.error_code === "Y10000") {
          res.data.datas.serviceInfo.service_price = JSON.parse(res.data.datas.serviceInfo.service_price)
          self.setData({
            serviceInfor: res.data.datas.serviceInfo
          })

        }
      },
      fail: function ({ errMsg }) {
        console.log('request fail', errMsg)
      }
    })
  },
  //判断是否有方案文件上传
  schemeInfoFn: function (schemeInfo) {
    if (schemeInfo == null || schemeInfo.length == 0) {
      return false;
    }
    let flag = false;
    for (var i = 0; i < schemeInfo.length; i++) {
      var el = schemeInfo[i];
      if (el.scheme_status != 3) {
        flag = true;
        break;
      }
    }
    return flag;
  },
  //判断方案文件是否审核了
  schemeInfoStatus: function (schemeInfo) {
    if (schemeInfo == null || schemeInfo.length == 0) {
      return false;
    }
    let flag = false;
    for (var i = 0; i < schemeInfo.length; i++) {
      var el = schemeInfo[i];
      if (el.scheme_status == 0) {
        flag = true;
        break;
      }
    }
    return flag;
  },
  //上传文件内容整理
  getFilesBySuffix: function (files, suffix) {
    if (files != null && files.length > 0) {
      var newFile = [];
      for (var i = 0; i < files.length; i++) {
        var file = files[i];
        if (file.old_name.endWith(suffix)) {
          newFile.push(file);
        }
      }
      return newFile;
    }
  },
  //设计法案数据封装
  handlerSchemes: function (schemes) {
    if (schemes != null && schemes.length > 0) {
      var newSchemes = [];
      for (var i = 0; i < schemes.length; i++) {
        var scheme = schemes[i];
        var files = scheme.list;
        scheme.stl_files = this.getFilesBySuffix(files, ".stl");
        scheme.pdf_files = this.getFilesBySuffix(files, ".pdf");
        newSchemes.push(scheme);
      }
      return newSchemes;
    }
  },
  // 查看测量方案
  seeMeasurement: function () {
    var url = '../file/measurement?id=' + this.data.id;
    wx.navigateTo({
      url: url
    })
  },
  // 查看发票信息
  seeInvoice: function () {
    var url = '../invoice/invoiceInfo?id=' + this.data.id;
    wx.navigateTo({
      url: url
    })
  },
  //查看下单信息
  seeOrderInfo: function () {
    var url = '../../placeOrdInfor/orderInfor/orderInfor?id=' + this.data.id;
    wx.navigateTo({
      url: url
    })
  },
  //复制订单编号
  clickCopy: function () {
    wx.setClipboardData({
      data: this.data.serviceInfo.order_no,
      success() {
        wx.showToast({
          title: '复制成功',
          icon: 'succes',
          duration: 1000,
          mask: true
        })
      }
    })
  },
  //查看CT数据
  model: function () {
    wx.showModal({
      title: 'CT数据要求',
      showCancel: false,
      confirmText: '知道了',
      confirmColor: '#4825BF',
      content: JSON.parse(this.data.serviceInfo.order_service_list[0].fileds).ct.ctRequirement,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        }
      }
    })
  },
  //订单取消原因绑定
  inputRemark: function (e) {
    this.setData({
      remarks: e.detail.value
    })
  },
  //取消订单
  cancelOrder: function () {
    this.setData({
      cancelPop: false
    })
  },
  //选择取消原因
  selectedReason: function (event) {
    let self = this
    let cancelBtn = self.data.cancelBtn
    for (var i = 0; i < self.data.cancelBtn.length; i++) {
      if (i == event.currentTarget.dataset.index) {
        cancelBtn[i].check = !cancelBtn[i].check
        self.setData({
          cancelIndex: i
        })
      } else {
        cancelBtn[i].check = false
      }
    }
    self.setData({
      cancelBtn: cancelBtn
    })
  },
  //弹窗选择原因取消按钮
  cancelPopOrder: function () {
    let self = this
    var remarks = self.data.cancelBtn[self.data.cancelIndex].title
    if (self.data.cancelIndex == 5) {
      remarks = self.data.remarks
    }
    var cancelData = {
      order_id: self.data.id,
      operation_type: 0,
      reason: {
        "order_status": self.data.serviceInfo.status,
        "remarks": remarks
      }
    }
    wx.request({
      url: wx.envConfig.host + '/order/closeOrderNew?params=' + JSON.stringify(cancelData) + '&cookiez=' + wx.getStorageSync('cookiez'),
      method: 'POST',
      success: function (res) {
        if (res.data.error_code === "Y10000") {
          self.setData({
            cancelPop: true
          })
          wx.showToast({
            title: '订单取消成功',
            icon: 'success',
            duration: 2000
          })
          self.getOrderDetail(self.data.id)
        }
      },
      fail: function ({ errMsg }) {
        console.log('request fail', errMsg)
      }
    })

  },
  //删除订单
  deleteOrder: function () {
    let self = this
    console.log(self.data.id)
    wx.showModal({
      title: '',
      confirmText: '是',
      cancelText: '否',
      cancelColor: '#4825BF',
      confirmColor: '#4825BF',
      content: '您确定要删除此订单?',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: wx.envConfig.host + '/order/deleteOrder?params=' + JSON.stringify({ "order_id": self.data.id }) + '&cookiez=' + wx.getStorageSync('cookiez'),
            method: 'POST',
            success: function (res) {
              if (res.data.error_code === "Y10000") {
                wx.navigateBack()
              }
            },
            fail: function ({ errMsg }) {
              console.log('request fail', errMsg)
            }
          })
        }
      }
    })
  },
  /**
  * 点击客服图标
  */
  customService: function () {
    let self = this
    self.setData({
      needHelp: !self.data.needHelp
    })
    console.log('needhelp', self.data.needHelp)
  },
  //查看手术设计方案
  seeDesignScheme: function (e) {
    let self = this
    let serviceInfo = self.data.serviceInfo
    serviceInfo.schemeInfo[e.currentTarget.dataset.index].seeScheme = !serviceInfo.schemeInfo[e.currentTarget.dataset.index].seeScheme
    self.setData({
      serviceInfo: serviceInfo
    })
  },
  /**
   * 审核方案
   */
  adopt: function (event) {
    let self = this
    let type = event.currentTarget.dataset.name == '手术设计方案' ? 'operation' : event.currentTarget.dataset.name == '产品设计方案' ? 'product' : 3
    self.setData({
      exmeData: {
        "scheme_status": 1,
        "scheme_id": event.currentTarget.dataset.id,
        "order_id": self.data.id,
        "order_status": self.data.serviceInfo.status,
        "schemetype": type,
        "index": event.currentTarget.dataset.index
      }
    })
    self.globalReview.auditWindow()
  },
  /**
   * 查看方案，分享方案
   */
  shareScheme: function (e) {
    console.log(e)
    let type = e.currentTarget.dataset.name == '手术设计方案' ? 'operation' : e.currentTarget.dataset.name == '产品设计方案' ? 'product' : 3
    let url = ''
    wx.showActionSheet({
      itemList: ['预览方案', '分享方案'],
      success: (res) => {
        var newtype = ''
        var pdfurl = ''
        if (e.currentTarget.dataset.pdfurl){
          for (var c = 0, purl; purl = e.currentTarget.dataset.pdfurl[c]; c++) {
            newtype = purl.old_name.substr(purl.old_name.lastIndexOf('.')).toLowerCase()
            console.log(newtype)
            if (newtype === '.pdf') {
              pdfurl = purl.name
            }
          }
        }
        
        if (res.tapIndex == 0) {
          if (e.currentTarget.dataset.type == 'pdf') {
            url = '/pages/exmeProgme/exmeProgme?pdfID=' + pdfurl
            wx.navigateTo({
              url: '../../exmeProgme/exmeProgme?pdfID=' + pdfurl
            })
          } else {
            url = '/pages/exmeProgme/exmeProgme?orderId=' + this.data.id + '&type=' + type
            wx.navigateTo({
              url: '../../exmeProgme/exmeProgme?orderId=' + this.data.id + '&type=' + type
            })
          }
        }
        if (res.tapIndex == 1) {
          if (e.currentTarget.dataset.type == 'pdf') {
            url = '/pages/exmeProgme/exmeProgme?pdfID=' + pdfurl
          } else {
            url = '/pages/exmeProgme/exmeProgme?orderId=' + this.data.id + '&type=' + type
          }
          this.setData({
            shareConfig: {
              orderId: this.data.id,
              type: type,          //方案类型  1:手术方案  2:产品方案  3:分割方案
              schemeId: e.currentTarget.dataset.schemeid,     //方案ID
              shareUrl: url
            },
            sharePopup: false
          })
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  //确认收货
  delivery: function () {
    let self = this
    wx.showModal({
      title: '',
      confirmText: '是',
      cancelText: '否',
      cancelColor: '#4825BF',
      confirmColor: '#4825BF',
      content: '是否确认收货',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: wx.envConfig.host + '/order/confirmReceiptOrder?params=' + JSON.stringify({ "order_id": self.data.id }) + '&cookiez=' + wx.getStorageSync('cookiez'),
            method: 'POST',
            success: function (res) {
              if (res.data.error_code === "Y10000") {
                self.getOrderDetail(self.data.id)
              }
            },
            fail: function ({ errMsg }) {
              console.log('request fail', errMsg)
            }
          })
        }
      }
    })
  },
  //弹出评论
  evaluation: function () {
    let self = this
    self.setData({
      modelPop: false
    })
  },
  // 提交评论
  submitEvaluation: function () {
    let self = this
    var data = {
      "order_id": self.data.id,
      "order_no": self.data.serviceInfo.order_no,
      "service_id": self.data.serviceInfo.service_id,
      "type": self.data.contentConfig.scoreArray[0].selected,
      "user_remarks": self.data.supDescribe
    }
    console.log(data)
    wx.request({
      url: wx.envConfig.host + '/order/insertOrderEvaluate?params=' + JSON.stringify(data) + '&cookiez=' + wx.getStorageSync('cookiez'),
      method: 'POST',
      success: function (res) {
        if (res.data.error_code === "Y10000") {
          self.getOrderDetail(self.data.id)
          self.setData({
            modelPop: true
          })
        }
      },
      fail: function ({ errMsg }) {
        console.log('request fail', errMsg)
      }
    })
  },
  //去支付
  goPay: function (e) {
    var url = '../../home/category/uploadCTdata/orderpay/orderpay?id=' + this.data.id + '&price=' + this.data.serviceInfo.pay_money
    wx.navigateTo({
      url: url
    })
  },
  //去聊天
  goToChat: function (e) {
    wx.navigateTo({
      url: '../../message/chat/chat?id=' + id + '&teamId=' + teamId
    })
  },
  //完善信息
  uploadCtData: function () {
    wx.navigateTo({
      url: '../../home/category/uploadCTdata/uploadCTdata?id=' + this.data.id + '&type=addFile'
    })
  },
  // 联系客服
  onlineService: function () { // 跳转到在线客服
    wx.navigateTo({
      url: '../../message/chat/chat' // 不带id为客服
    })
  },
  // 订单聊天
  orderlineService: function () { // 跳转到在线客服
    console.log(this.data.serviceInfo)
    wx.navigateTo({
      url: '../../message/chat/chat?id=' + 'team-' + this.data.serviceInfo.msg_room + '&teamId=' + this.data.serviceInfo.msg_room // 不带id为客服
    })
  },
  // 订单聊天
  callPhone: function () { // 跳转到在线客服
    console.log(wx.getStorageSync('userInfo').id)
    wx.navigateTo({
      url: '../../message/phone/phone?orderId=' + this.data.id + '&callUid=' + wx.getStorageSync('userInfo').uid + '&recUid=' + this.data.serviceInfo.user_designer_uid // 不带id为客服
    })
  }
})